<template >

  <div >
    <a-breadcrumb style="font-family: 仿宋">
      <a-breadcrumb-item>业务系统</a-breadcrumb-item>
      <a-breadcrumb-item>洁净检测</a-breadcrumb-item>
      <a-breadcrumb-item>历史数据</a-breadcrumb-item>
    </a-breadcrumb>
  </div>
  <div style="padding: 0px 36px;" ref="pdfContent" v-if="showContent" class="pdf-content">
    <div style="margin-top: 20px;overflow: hidden;">
      <div style="float: left">
        <a-form layout="inline">
          <a-form-item>
            <a-radio-group v-model:value="selectButton" @change="onRadioChange">
              <a-radio-button value="today">今日</a-radio-button>
              <a-radio-button value="week">近一周</a-radio-button>
              <a-radio-button value="month">近一月</a-radio-button>
            </a-radio-group>
          </a-form-item>
          <a-form-item>
            <a-space direction="vertical">
              <a-range-picker
                  :show-time="{ format: 'HH:mm' }"
                  format="YYYY-MM-DD HH:mm"
                  :placeholder="['开始时间', '结束时间']"
                  @change="onChange"
                  @ok="onOk"
              />
            </a-space>
          </a-form-item>
          <a-form-item>
            <a-space>
              产品id:
              <a-select
                  v-model:value="productId"
                  style="width: 120px"
                  :options="productList"
              >
              </a-select>
              设备id:
              <a-select
                  v-model:value="deviceId"
                  style="width: 120px"
                  :options="deviceList"
              >
              </a-select>
            </a-space>
          </a-form-item>
          <a-form-item>
            <a-button type="primary">
              搜索
              <SearchOutlined/>
            </a-button>
          </a-form-item>
        </a-form>
      </div>
      <div style="float: right;">
        <a-form layout="inline">
          <a-form-item style="margin-right: 20px;">
            <a-button @click="exportToExcel" >
              <template #icon>
                <UploadOutlined />
              </template>
              导出Excel
            </a-button>
          </a-form-item>
          <a-form-item >
            <a-button @click="prepareAndExportPDF">
              导出PDE
              <template #icon>
                <DownloadOutlined />
              </template>
            </a-button>
          </a-form-item>
        </a-form>
      </div>
    </div>
    <div style="margin-top: 20px; border:1px solid #999;">
      <div style="background-color: #EEEEEE;height: 50px;border:1px solid #999;">
        <button @click="addRow">+</button>
      </div>
      <div style="background-color: #FFFFFF;height: 500px; ">
        <div>

          <table border="1">
            <thead>
            <tr>
              <th>创建时间</th>
              <th>设备ID</th>
              <th>0.3um</th>
              <th>0.5um</th>
              <th>1um</th>
              <th>3um</th>
              <th>5um</th>
              <th>10um</th>
              <th>流量</th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="(row, index) in rows" :key="index">
              <td>{{ new Date().toLocaleString() }}</td> <!-- 这里可以改成输入框让用户输入时间，为了简化直接用当前时间 -->
              <td><input type="string" v-model="row.deviceIdChecked"></td>
              <td><input type="checkbox" v-model="row.particleSizes['0.3um']"></td>
              <td><input type="checkbox" v-model="row.particleSizes['0.5um']"></td>
              <td><input type="checkbox" v-model="row.particleSizes['1um']"></td>
              <td><input type="checkbox" v-model="row.particleSizes['3um']"></td>
              <td><input type="checkbox" v-model="row.particleSizes['5um']"></td>
              <td><input type="checkbox" v-model="row.particleSizes['10um']"></td>
              <td><input type="number" v-model.number="row.flowRate"></td>
            </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>

</template>

<script>
import { ref } from 'vue';
import {SearchOutlined,DownloadOutlined,UploadOutlined} from '@ant-design/icons-vue';
import jsPDF from 'jspdf';
import html2canvas from 'html2canvas';
import * as XLSX from 'xlsx';
export default {
  name: "HistoryData",
  components: {
    SearchOutlined,
    UploadOutlined,
    DownloadOutlined
  },
  setup() {
    const rows = ref([]);

    const addRow = () => {
      rows.value.push({
        deviceIdChecked:null,
        particleSizes: {
          '0.3um': false,
          '0.5um': false,
          '1um': false,
          '3um': false,
          '5um': false,
          '10um': false,
        },
        flowRate: null,
      });
    };
        return {
      rows,
          addRow,
    };
  },
  data() {
    return {
      showContent: true,
      selectButton: 'week',
      productId: 'JC-6FZ',
      productList: [{value: "JC-6FZ", label: "在线浮游菌采样器-JC-6FZ"},
        {value: "WD4120A", label: "风速测量仪-WD4120A"},
        {value: "JC-601", label: "尘埃粒子计数器-JC-601"},
        {value: "JC-B-6", label: "多点系统变送器-JC-B-6"},
      ],
      deviceId: 'JC-6FZ',
      // deviceList:[{value:"p1-d1",label:"商品1-设备1"},{value:"p1-d2",label:"商品1-设备2"}],
      deviceDatas: {
        "JC-6FZ": [{value: "JC-6FZ", label: "JC-6FZ-00"}],
        "WD4120A": [{value: "WD4120A", label: "风速1"}, {value: "WD4120A211", label: "风速2"}],
        "JC-601": [{value: "JC-601", label: "粒子1"}, {value: "JC-60111", label: "粒子2"}],
        "JC-B-6": [{value: "JC-B-6", label: "警报灯"}, {value: "JC-B-611", label: "样间多点系统变速器"},{value: "JC-B-622", label: "二间多点系统变速器"}],
      }
    }
  },
  computed: {
    // 计算属性的 getter
    deviceList: function () {
      // `this` 指向 vm 实例
      return this.deviceDatas[this.productId]
    }
  },
  watch: {
    productId(newVal, oldVal) {
      // 处理数据变化后的操作
      console.log('productId属性发生变化了，新值为:', newVal, '旧值为:', oldVal);
      this.deviceId = this.deviceDatas[newVal][0].value
    }
  },
  methods: {
    onRadioChange(e) {
      console.log('Radio changed:', e.target.value);
    },
    onChange(value, dateString) {
      console.log('Selected Time: ', value);
      console.log('Formatted Selected Time: ', dateString);
    },

    onOk(value) {
      console.log('onOk: ', value);
    },
    async prepareAndExportPDF() {
      // 等待 Vue 更新 DOM（如果需要的话）
      await this.$nextTick();

      // 检查元素是否存在
      const content = this.$refs.pdfContent;
      if (!content || !(content instanceof HTMLElement)) {
        console.error('Element not found or not attached to DOM');
        return;
      }

      try {
        // 使用 html2canvas 渲染元素为画布
        const canvas = await html2canvas(content);
        const imgData = canvas.toDataURL('image/png');


        const pdf = new jsPDF();
        const imgWidth = 210; // PDF 宽度，单位毫米
        const imgHeight = (canvas.height * imgWidth) / canvas.width; // 保持宽高比
        pdf.addImage(imgData, 'PNG', 0, 0, imgWidth, imgHeight);
        pdf.save('document.pdf');
      } catch (error) {
        console.error('Error exporting to PDF:', error);
      }
    },
    exportToExcel() {
      // 创建工作簿和工作表
      const wb = XLSX.utils.book_new();
      const ws = XLSX.utils.json_to_sheet([
        {id: 'JC-B-6', name: '多点系统变送器-JC-B-6',
          photoUrl: 'http://119.136.32.69:9000/images/device/instance/device-card.png',
          describe: '多点系统变送器 JC-B-6',
          classifiedId: '-301-',
          classifiedName: '智能园区',
          messageProtocol: 1780826262248849408,
          protocolName: 'HJ-消息协议',
          metadata: ":",
          transportProtocol: "MQTT"},
        {id: 'JC-6FZ', name: '在线浮游菌采样器-JC-6FZ',
          photoUrl: 'http://119.136.32.69:9000/images/device/instance/device-card.png',
          describe: '在线浮游菌采样器-JC-6FZ',
          classifiedId: '-111-',
          classifiedName: '智能园区',
          messageProtocol: 1780826262248849408,
          protocolName: 'HJ-消息协议',
          metadata: ":",
          transportProtocol: "MQTT"},
        {id: 'WD4120A', name: '风速测量仪-WD4120A',
          photoUrl: 'http://119.136.32.69:9000/images/device/instance/device-card.png',
          describe: '在线浮游菌采样器-JC-6FZ',
          classifiedId: '-301-',
          classifiedName: '智能园区',
          messageProtocol: 1780826262248849408,
          protocolName: 'HJ-消息协议',
          metadata: ":",
          transportProtocol: "MQTT"},
        {id: 'WD4120A', name: '风速测量仪-WD4120A',
          photoUrl: 'http://119.136.32.69:9000/images/device/instance/device-card.png',
          describe: '在线浮游菌采样器-JC-6FZ',
          classifiedId: '-301-',
          classifiedName: '智能园区',
          messageProtocol: 1780826262248849408,
          protocolName: 'HJ-消息协议',
          metadata: ":",
          transportProtocol: "MQTT"},
      ]);
      // 将工作表添加到工作簿
      XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
      // 生成 Excel 文件并触发下载
      XLSX.writeFile(wb, 'data.xlsx');
    },
  },
}
</script>

<style scoped>
table {
  width: 100%;
  border-collapse: collapse;
}
.pdf-content {
}
th, td {
  border: 1px solid black;
  padding: 8px;
  text-align: left;
}

button {
  margin-bottom: 10px;
}
.ant-radio-button-checked + span {
  color: #ffffff;
}
</style>